package com.lawrence.util;

import java.io.FileReader;
import java.sql.Connection;
import java.sql.DriverManager;
import java.util.Properties;

/**
 * 将重复的jdbc代码提取封装为工具类
 */
public class JDBCUtil {

    //1.声明连接数据库的变量
    private static String driver;
    private static String url;
    private static String user;
    private static String password;

    //2.加载配置文件
    static {
        try {
            Properties properties = new Properties();
            FileReader fileReader = new FileReader("src/main/resources/db.properties");
            properties.load(fileReader);
            driver = properties.getProperty("driver");
            url = properties.getProperty("url");
            user = properties.getProperty("user");
            password = properties.getProperty("password");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static Connection getConnection() throws Exception {
        //3.加载驱动
        Class.forName(driver);
        //2.建立连接
        Connection connection = DriverManager.getConnection(url,user,password);
        //3.返回连接
        return connection;
    }
}
